﻿using Abp.vNext.WT.WebApi.Issues;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.Uow;

namespace Abp.vNext.WT.WebApi.EntityFrameworkCore
{
    public class IssueRepository_Tests : WebApiEntityFrameworkCoreTestBase
    {
        private readonly IRepository<Issue, Guid> _issueRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IDbContextProvider<WebApiDbContext> _dbContextProvider;

        public IssueRepository_Tests()
        {
            _issueRepository = GetRequiredService<IRepository<Issue, Guid>>();
            _unitOfWorkManager = GetRequiredService<IUnitOfWorkManager>();
            _dbContextProvider = GetRequiredService<IDbContextProvider<WebApiDbContext>>();
        }

        public async Task Should_Query_By_Title()
        {
            // 所有数据库操作都必须在一个工作单元作用域内执行
            // 当你测试应用服务方法时, 工作单元的作用域将是应用服务方法的作用域.
            // 如果你正在测试仓储方法, 那么工作单元作用域将是你的仓储方法的作用域.
            #region 会出错
            //IQueryable<Issue> queryable = await _issueRepository.GetQueryableAsync(); // 存储作用域
            //var issue = queryable.FirstOrDefaultAsync(i => i.Title == "My issue title");// 存储方法作用域
            //issue.ShouldNotBeNull();
            #endregion

            // 使用了IUnitOfWorkManager服务来创建一个工作单元作用域，让其在一个工作单元作用域
            using (var uow = _unitOfWorkManager.Begin())
            {
                IQueryable<Issue> queryable = await _issueRepository.GetQueryableAsync();
                var issue = queryable.FirstOrDefaultAsync(i => i.Title == "My issue title");
                issue.ShouldNotBeNull();
                await uow.CompleteAsync();
            }
        }

        public async Task Should_WebApiDbContext_Query_By_Title()
        {
            using (var uow = _unitOfWorkManager.Begin())
            {
                var dbContext = await _dbContextProvider.GetDbContextAsync();
                var issue = await dbContext.Issues.FirstOrDefaultAsync(i => i.Title == "My issue title");
                issue.ShouldNotBeNull();
                await uow.CompleteAsync();
            }
        }
    }

}
